#!/usr/bin/env python
# -*- coding:utf-8 -*-
from datetime import datetime
import sys

import pymongo
from scpy.logger import get_logger


logger = get_logger(__file__)

reload(sys)
sys.setdefaultencoding("utf-8")

MONGO_HOST, MONGO_PORT = '192.168.31.121', 27017
MONGO_CONN = pymongo.MongoClient(MONGO_HOST, MONGO_PORT)


def parse_city_id(city):
    try:
        return MONGO_CONN['crawler_car']['city'].find_one({"city": city})
    except Exception, e:
        logger.exception(e)
        return None


def parse_ltime(string):
    if not string:
        raise Exception('license time error')
    year, month = [int(x) for x in string.split('-')]
    if not (1 <= month <= 12):
        raise Exception('month error!!!')
    if not (1970 <= year <= datetime.now().year):
        raise Exception('year error!!!')
    return year, month


def parse_car(car):
    try:
        cars = [car for car in MONGO_CONN['crawler_car']['car'].find(({'model': {"$regex": car}}))]
        if cars:
            return cars
        cars = [car for car in MONGO_CONN['crawler_car']['car'].find(({'carName': {"$regex": car}}))]
        if cars:
            return cars
    except Exception, e:
        logger.exception(e)
        return None


